<?php

/**
 * 微信Oauth过来后会走这个流程
 * 检查用户记录是否完善 -> 完善用户数据->登录
 * Author: changziming  
 */

namespace Home\Controller;

use Think\Controller;
use Think\Exception; 

class PublicController extends Controller {

    /**
     * Oauth认证后会先这样创建用户 
     * 然后进行微信登录操作 
     * @return [type] [description]
     */
    public function oauthdo() {  
        # 获取微信公众号信息 
        $wxinfo = mpc() ;  
        if ( !empty($wxinfo) ) {
            $config['token'] = $wxinfo['token'];
            $config['appid'] = $wxinfo['appid'];
            $config['appsecret'] = $wxinfo['appsecret'];
            if (isset($_GET['code'])) {
                Vendor('Wechat.Wechat');
                $weObj  = new \Wechat($config);
                $weObj->checkAuth(); 
                $token  = $weObj->getOauthAccessToken(); 
                $result = $weObj->getOauthUserinfo($token['access_token'],$token['openid']);  //显示方式此行有效
                $ret    = M('member')->field('uid')->where('openid = "' . $token['openid'] . '"')->find();
                if ( empty($ret) ) { 
                    $nickname   = empty($result['nickname']) ? '用户-' . $this->getMaxUid() : $result['nickname'];
                    $ct_uid     = M('member')->add(array('unionid' => $result['unionid'], 'openid' => $result['openid'], 'nickname' => $nickname, 'avatar' => $result['headimgurl'],'reg_time'=>time(),'last_login_time'=>time(),'last_active_time'=>time(),'status'=>1));
                    if ( $ct_uid > 1 ) {
                        D('Home/Member')->login( $ct_uid ); 
                    } 
                }else { 
                    D('Home/Member')->login($ret['uid']);    
                }
                # 到此 openID与平台本身Member 数据都创建完毕 并且已经关联  
                $redirect_url = session('redirect_url') ; 
                if ( !$redirect_url ) {
                    # 默认的跳转地址 用户主页吧. 
                    $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Index/index'); 
                }   
                header('Location:' . $redirect_url, true, 302);
                exit(); 
            }
        }
    } 
    
    /**
     * 获取一个最大值 为了起名用 
     * @return [type] [description]
     */
    private function getMaxUid() {
        $nown = M('Member')->max('uid');
        return $nown+1 ;
    }

     /**
     * xml => array
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    protected function xml_to_array($xml){                                                        
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
        return $values;                                 
    }
}
